package at.fhj.swd.pse.beans;

import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import at.fhj.swd.pse.entities.Community;
import at.fhj.swd.pse.helper.CommunityManager;

/**
 * 
 * @author Robert Puerer
 * @author Helmut Kopf
 *
 */

@Named
@Stateless
@ManagedBean
public class CommunityBean {
	@Inject
	private Logger log;
	
	@Inject
	private CommunityManager cm;

	@Named
	private List<Community> communities;
		
	private Community currentCommunity;

	public CommunityBean() {

	}

	@PostConstruct
	public void init() {
		log.info("CommunityBean.init invoked");
	}	
			
	public Community getCurrentCommunity() {
		log.info("CommunityBean.getCurrentCommunity invoked");
				
		initCurrentCommunity();
		
		return this.currentCommunity;
	}

	public List<Community> getCommunities() {
		return cm.getCommunities();
	}

	private void initCurrentCommunity() {
		log.info("CommunityBean.initCurrentCommunity invoked");
		
		FacesContext context = FacesContext.getCurrentInstance();
	    Map<String, String> requestMap = context.getExternalContext().getRequestParameterMap();
	    
	    if (requestMap != null) {
	    	log.info("requestMap is not null");	    	
	    	if (requestMap.containsKey("id")) {	    		
			    String sid = (String) requestMap.get("id");
			    log.info("id = " + sid);
			    
			    int id = Integer.parseInt(sid);
			    
			    if (this.currentCommunity != null) {
			    	if (this.currentCommunity.getID() == id) {
			    		return;
			    	}
			    }
			    
		    	this.currentCommunity = this.cm.getCommunity(id);
		    	
				if (this.currentCommunity != null) {
					log.info("Current Community found");
				}
	    	}
	    }		
	}	
}
